package com.aube.plugin.episode.list;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.aube.plugin.episode.VideoListItem;
import com.aube.plugin.origin.R;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.dynamicload.BlurViewDecorator;
import com.huyn.baseframework.dynamicload.DLBridge;
import com.huyn.baseframework.dynamicload.DLLayout;
import com.huyn.baseframework.dynamicload.DynamicLoaderHelper;
import com.huyn.baseframework.dynamicload.IPositionListener;
import com.huyn.baseframework.dynamicload.IPositionManager;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.CategorySimple;
import com.huyn.baseframework.net.OpenApi;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.SysUtil;
import com.ryg.dynamicload.DLBasePluginFragmentActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by huyaonan on 16/5/26.
 */
public class VideoListActivity extends DLBasePluginFragmentActivity {

    public static final String CATEGORY = "CATEGORY";

    private static final int MAX_NUM  =10;

    private CustomRecyclerView mRecyclerView;
    private LinearLayoutManager mLayoutManager;
    private BlurViewDecorator mBlurview, mBlurTop;

    private Category mCate;

    private ParallaxListTopBarLayout mParallaxTop;

    private CategoryAdapter mAdapter;

    private List<Object> mContent;

    private View mBlurMask;
    private ImageView mBg, mHead;
    private ImageView mBgReal, mHeadReal;

    private FrameLayout mBlurContainer;

    private boolean mDataLoadFinished = false;
    private boolean mDataLoading = false;
    private String mLastId="";
    private int mLastIndex = -1;
    private int mItemMargin = 0;

    private int mLastScrollY = 0;
    private int targetHeight;
    private int statusHeight = 0;
    private int topbarheight = 200;

    private int totalHeight = 0;

    private boolean autoAnim = true;

    private IPositionManager iPositionManager = new IPositionManager() {
        @Override
        public void add(IPositionListener iPositionListener) {

        }

        @Override
        public void remove(IPositionListener iPositionListener) {

        }

        @Override
        public void listener(int i) {

        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_category_list);

        Intent intent = getIntent();
        mCate = (Category) intent.getSerializableExtra(CATEGORY);

        mBg = (ImageView) findViewById(R.id.bg);
        mHead = (ImageView) findViewById(R.id.detail_header);
        mBgReal = (ImageView) findViewById(R.id.bg_real);
        mHeadReal = (ImageView) findViewById(R.id.detail_header_real);

        mBlurMask = findViewById(R.id.blur_mask);

        setImgWithRes(mBg, R.drawable.bk_default);
        setImgWithRes(mHead, R.drawable.bk_default);
        setImgWithRes(mBgReal, R.drawable.bk_default);
        setImgWithRes(mHeadReal, R.drawable.bk_default);
        setBgWithRes(mBlurMask, R.drawable.gradient_blur_top);

        mRecyclerView = (CustomRecyclerView) findViewById(R.id.detail_list);
        mRecyclerView.setHasFixedSize(true);

        mLayoutManager = new LinearLayoutManager(that);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                totalHeight += dy;
                int y = totalHeight;
                if (y == mLastScrollY)
                    return;
                mLastScrollY = y;
                if (y >= targetHeight - topbarheight - statusHeight) {
                    mParallaxTop.updateTitleOffset(targetHeight - topbarheight - statusHeight);
                } else {
                    mParallaxTop.updateTitleOffset(y);
                }

                int targetY = targetHeight - y;
                mBlurview.setTranslationY(targetY < 0 ? 0 : targetY);
                mBlurview.invalidate();

                mBlurTop.setTranslationY(-y);
                float alpha = 0;
                if (y > targetHeight - topbarheight - statusHeight) {
                    alpha = 1f;
                } else {
                    alpha = y * 1f / (targetHeight - topbarheight - statusHeight);
                }
                mBlurTop.setAlpha(alpha);
                mBlurTop.invalidate();

                mBlurMask.setTranslationY(targetY < 0 ? -targetHeight : -y);
                mBlurMask.setAlpha(1 - alpha);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (mDataLoadFinished || mAdapter == null)
                    return;
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (mLayoutManager.findLastVisibleItemPosition() == mAdapter.getItemCount() - 1) {
                        onLoadMore();
                    }
                }
            }
        });

        mBlurContainer = (FrameLayout) findViewById(R.id.blur_container);

        try {
            mBlurview = getBlurView(false);
            View view = findViewById(R.id.bg_layout);
            mBlurview.setBlurredView(view);
            mBlurview.setOverlayColor(getResources().getColor(R.color.blur_color));

            mBlurTop = getBlurView(false);
            mBlurTop.setBlurredView(view);
            mBlurTop.setOverlayColor(getResources().getColor(R.color.blur_color));

            mBlurContainer.addView(mBlurview, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            mBlurContainer.addView(mBlurTop, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        } catch (Exception e) {
            e.printStackTrace();
        }

        mParallaxTop = (ParallaxListTopBarLayout) findViewById(R.id.parallax_topbar);

        statusHeight = SysUtil.getStatusHeight(that);
        topbarheight = getResources().getDimensionPixelOffset(R.dimen.actionbar_height);
        targetHeight = getResources().getDimensionPixelOffset(R.dimen.category_list_head_height);

        mRecyclerView.setPadding(0, topbarheight+statusHeight, 0, 0);

        RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) mParallaxTop.getLayoutParams();
        params2.height = targetHeight;
        mParallaxTop.setTopbarHeight(topbarheight);
        mParallaxTop.updateTitle(mCate.modelName);

        mBlurview.setTranslationY(targetHeight);

        FrameLayout.LayoutParams topParams = (FrameLayout.LayoutParams) mBlurTop.getLayoutParams();
        topParams.height = targetHeight;

        RelativeLayout.LayoutParams params3 = (RelativeLayout.LayoutParams) mBlurMask.getLayoutParams();
        params3.height = targetHeight;

        mRecyclerView.setITimerResetCallback(new CustomRecyclerView.IAutoAnimEndCallback() {
            @Override
            public void end() {
                if(mAdapter != null && autoAnim)
                    autoAnim = false;
            }
        });

        mBlurMask.setAlpha(1f);
        mBlurTop.setAlpha(0f);

        mItemMargin = getResources().getDimensionPixelOffset(R.dimen.scroll_item_margin);
        getData();
    }

    private void onLoadMore() {
        if(mDataLoading)
            return;
        mDataLoading = true;
        getData();
    }

    public View inflate(int id, ViewGroup root, boolean attachToRoot) {

        final XmlResourceParser parser = getResources().getLayout(id);
        try {
            return LayoutInflater.from(that).inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

    private class CategoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private static final int TYPE_HEAD = 1;
        private static final int TYPE_CONTENT = 2;

        private Context context;

        public CategoryAdapter(Context context) {
            this.context = context;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            switch (i) {
                case TYPE_HEAD:
                    View head = inflate(R.layout.layout_item, viewGroup, false);
                    return new BlankHeadHolder(head);
                case TYPE_CONTENT:
                    RelativeLayout view = (RelativeLayout) inflate(R.layout.layout_item, viewGroup, false);
                    VideoListItem dlView = (VideoListItem) DynamicLoaderHelper.loadTargetLayout(context, mPluginPackage, VideoListItem.class.getName());
                    if(dlView != null) {
                        dlView.initData(mCate);
                        view.addView(dlView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                    }
                    return new VideoHolder(view, dlView);
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
            if(viewHolder == null)
                return;
            if(viewHolder instanceof VideoHolder) {
                VideoHolder videoHolder = (VideoHolder) viewHolder;
                boolean anim = false;
                if (i > mLastIndex) {
                    mLastIndex = i;
                    anim = true;
                }

                videoHolder.init(getData(i), anim, autoAnim ? (i-1)*200 : 0);
                if (i == getItemCount() - 1)
                    videoHolder.setPadding(true);
                else
                    videoHolder.setPadding(false);
            } else if(viewHolder instanceof BlankHeadHolder) {
                ((BlankHeadHolder) viewHolder).init();
            }
        }

        public Object getData(int pos) {
            if(mContent == null || pos < 0)// || pos >= mContent.size())
                return null;
            if(pos == 0)
                return null;
            return mContent.get((pos-1));//%mContent.size());
//            return mContent.get(mContent.size()-pos);
        }

        @Override
        public int getItemCount() {
//            return (mContent == null ? 0 : mContent.size()) * 10 + 1;
            return mContent == null ? 0 : mContent.size() + 1;
        }

        @Override
        public int getItemViewType(int position) {
            if(position == 0)
                return TYPE_HEAD;
            return TYPE_CONTENT;
        }
    }

    private class VideoHolder extends RecyclerView.ViewHolder {

        private View mRoot;
        private DLLayout mView;

        public VideoHolder(View view, DLLayout itemView) {
            super(view);
            this.mRoot = view;
            this.mView = itemView;
        }

        public void init(Object object, boolean anim, int delay) {
            if(mView != null) {
                if(anim)
                    mView.registToManager(iPositionManager);
                mView.setDLBridge(getBridge());
                mView.fillData(object);

                if (anim)
                    mView.notifyAnim(delay);
            }
        }

        public void setPadding(boolean addBottomPaddding) {
            mRoot.setPadding(0, 0, 0, addBottomPaddding?mItemMargin:0);
        }
    }

    private class BlankHeadHolder extends RecyclerView.ViewHolder {

        private ViewGroup mRoot;

        public BlankHeadHolder(View itemView) {
            super(itemView);
            this.mRoot = (ViewGroup) itemView;
        }

        public void init() {
            View view = new View(that);
            mRoot.addView(view, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelOffset(R.dimen.category_list_head_height)-getPadding()));
        }

    }

    private DLBridge getBridge() {
        return (DLBridge) that;
    }

    private int getPadding() {
        return topbarheight+statusHeight;
    }

    /**
     * 模块内容接口
     * templateCode(index | actor)
     * ostype(iphone|android)
     * modelCode（template接口中获取）
     * relatedId（有就传，比如嘉宾）
     * lastId（分页用，第一次可不传，当前页最后一个id）
     * maxnum（一页最大条数）
     */
    public void getData() {
        HashMap<String, String> params = new HashMap<>();
        params.put(OpenApi.API_METHOD, OpenApi.MODULE_MORE);
        params.put("templateCode", mCate.templateType);
        params.put("modelCode", mCate.modelCode);
        params.put("relatedId", mCate.relatedId);
        if(StringUtils.isNotBlank(mLastId))
            params.put("lastId", mLastId);
        params.put("maxnum", MAX_NUM + "");
        params.put("subModelCode", mCate.subModelCode);

        exeHttpRequest(params, CategoryListModel.class, null, new Response.Listener<CategoryListModel>() {
            @Override
            public void onResponse(CategoryListModel response) {
                mDataLoading = false;
                if(response == null || !response.success())
                    return;
                setupData(response);
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                mDataLoading = false;
            }

            @Override
            public void onStart() {
                mDataLoading = true;
            }
        });
    }

    public void setupData(CategoryListModel model) {
        if(model.data == null) {
            mDataLoadFinished = true;
            return;
        }
        List<Object> contents = null;
        for(CategoryImp category : model.data) {
            if("modelHead".equalsIgnoreCase(category.modelCode)) {
                if(mAdapter == null) {
                    ImageLoader.getInstance(that).preloadBitmap(category.headPic.picurl, new ImageLoader.IPreloadCallback<Bitmap>() {
                        @Override
                        public void onSuccess(Bitmap bitmap) {
                            mBgReal.setImageBitmap(bitmap);
                            mHeadReal.setImageBitmap(bitmap);
                            final ValueAnimator anim = ValueAnimator.ofFloat(1, 0);
                            anim.setDuration(500);
                            anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                                @Override
                                public void onAnimationUpdate(ValueAnimator animation) {
                                    float alpha = (float) animation.getAnimatedValue();
                                    mBg.setAlpha(alpha);
                                    mHead.setAlpha(alpha);
                                    mBlurview.invalidate();
                                }
                            });
                            anim.addListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    mBg.setVisibility(View.GONE);
                                    mHead.setVisibility(View.GONE);
                                }
                            });
                            anim.start();
                        }

                        @Override
                        public void onFail() {

                        }
                    });
                }
            } else {
                if(StringUtils.isBlank(mCate.launchclass)) {
                    mCate.launchclass = category.launchclass;
                    mCate.modelName = category.modelName;

                    mParallaxTop.updateTitle(mCate.modelName);
                }

                contents = category.dataDetail;
                mLastId = category.lastid;
//                if(contents.size() < MAX_NUM)
//                    mDataLoadFinished = true;
                if(StringUtils.isBlank(mLastId))
                    mDataLoadFinished = true;
            }
        }
        if(mAdapter == null) {
            if(contents != null)
                mContent = contents;
            mAdapter = new CategoryAdapter(that);
            mRecyclerView.setAdapter(mAdapter);
        } else {
            if(mContent == null)
                mContent = new ArrayList<>();
            if(contents != null) {
                mContent.addAll(contents);
                mAdapter.notifyDataSetChanged();
            }
        }
    }

}
